package com.imooc.apigateway.filter;

import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import org.springframework.stereotype.Component;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SERVLET_DETECTION_FILTER_ORDER;

/**
 * 限流过滤
 * @author steve
 * @date 2020/6/24 14:53
 */
@Component
public class RateLimitFilter extends ZuulFilter {
    /**
     * 谷歌guava实现令牌桶算法
     * 每秒钟往令牌桶放100个令牌
     */
    private static final RateLimiter RATE_LIMITER = RateLimiter.create(100);

    @Override
    public String filterType() {
        //前置限流
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        //限流优先级必须最高
        return SERVLET_DETECTION_FILTER_ORDER - 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        //tryAcquire()不带参数，是取1个令牌
        if (!RATE_LIMITER.tryAcquire()) {
            //如果没有取到令牌，则抛异常
            throw new RuntimeException();
        }
        return null;
    }
}
